package com.hbu.housingbrokerug.activities;

import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.fedorvlasov.lazylist.LazyAdapter;
import com.hbu.housingbrokeruganda.Parser.JSONParser;
import com.hub.R;
import com.nostra13.universalimageloader.core.DisplayImageOptions;

/**
 * @author Lubwama Samuel(lubwamasamuel3[at]gmail[dot]com)
 */
public class Search extends Activity {
	private ProgressDialog pDialog;
	ListView list;
	LazyAdapter adapter;
	int sizeOfArray = 0;
	EditText editor;
	Button search_button;
	String result = "";
	int arraysize;
	JSONParser jParser = new JSONParser();
	TextView messageSearch;

	parserFromUrl parser = new parserFromUrl();

	public String[][] IMAGES;

	DisplayImageOptions options = parser.getOptions();
	public String ipOrDomain = parser.getIpOrDomain();

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.search_main);
		 

		search_button = (Button) findViewById(R.id.search_ok);

		search_button.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Bundle bundle=getIntent().getExtras();
				editor = (EditText) findViewById(R.id.searchform);
				list = (ListView) findViewById(R.id.listViewAllunits_search);
				list.clearChoices();
				// TODO Auto-generated method stub
				IMAGES = new String[][] {};
				new getAllHousingUnitInformation(editor.getText().toString(),bundle.getString("CATEGORY_ID"))
						.execute();
			}
		});

	}

	@Override
	public void onBackPressed() {
		Bundle bundle = getIntent().getExtras();
		Intent intentSearch = new Intent(this, Main.class);
		intentSearch.putExtra("CATEGORY_ID", bundle.getString("CATEGORY_ID"));
		intentSearch.putExtra("CATEGORY_NANE",
				bundle.getString("CATEGORY_NAME"));
		startActivity(intentSearch);
		finish();
		return;
	}

	public void onDestroy() {
		try {
			list.setAdapter(null);
		} catch (Exception e) {

		}
		super.onDestroy();
	}

	// getting one unit
	private void startingSingleUnit(int position) {
		// getting values from selected ListItem

		// Starting new intent
		Intent intent = new Intent(getApplicationContext(), SingleUnit.class);
		// sending pid to next activity
		intent.putExtra("UNIT_ID", IMAGES[position][0]);
		intent.putExtra("UNIT_DISTRICT", IMAGES[position][2]);
		intent.putExtra("UNIT_CITY", IMAGES[position][3]);
		intent.putExtra("UNIT_TOWN", IMAGES[position][4]);
		intent.putExtra("UNIT_VILLAGE", IMAGES[position][5]);
		intent.putExtra("UNIT_LATITUDE", IMAGES[position][6]);
		intent.putExtra("UNIT_LONGITUDE", IMAGES[position][7]);
		intent.putExtra("UNIT_CATEGORY", IMAGES[position][8]);
		intent.putExtra("UNIT_COST", IMAGES[position][9]);
		intent.putExtra("LANDLORD_FIRSTNAME", IMAGES[position][10]);
		intent.putExtra("LANDLORD_LASTNAME", IMAGES[position][11]);
		intent.putExtra("CONTACTS", IMAGES[position][12]);
		// starting new activity and expecting some response back
		startActivityForResult(intent, 100);

	}

	public class getAllHousingUnitInformation extends
			AsyncTask<String, String, String> {
		String categoryId="";
		public getAllHousingUnitInformation(String string, String string2) {
		categoryId=string2;
		}

		protected void onPreExecute() {
			super.onPreExecute();
			pDialog = new ProgressDialog(Search.this);
			pDialog.setMessage("Loading Houses From Server. Please wait...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();
		}

		@Override
		protected String doInBackground(String... params) {
			final String TAG_SUCCESS = "success";
			final String HOUSING_UNIT = "housing_units";
			try {
				editor = (EditText) findViewById(R.id.searchform);
				Log.d("EDITOR VALUE", editor.getText().toString());
				JSONObject json2 = jParser.makeHttpRequest((parser
						.getIpOrDomain() + parser.getQueryFile()).toString(),
						"GET", parser.getParametersSearch(editor.getText()
								.toString(),categoryId));
				int success = json2.getInt(TAG_SUCCESS);

				Log.d("SUCCESS TAG", String.valueOf(json2.getInt(TAG_SUCCESS)));
				if (success == 1) {
					JSONArray jArray = json2.getJSONArray(HOUSING_UNIT);
					IMAGES = new String[jArray.length()][13];
					for (int i = 0; i < jArray.length(); i++) {
						JSONObject json1 = jArray.getJSONObject(i);
						/* 1 */IMAGES[i][0] = json1.getString("unit_id");
						/* 2 */IMAGES[i][1] = parser.getIpOrDomain()
								+ json1.getString("urls_image");
						/* 3 */IMAGES[i][2] = json1.getString("district");
						/* 4 */IMAGES[i][3] = json1.getString("city");
						/* 5 */IMAGES[i][4] = json1.getString("town");
						/* 6 */IMAGES[i][5] = json1.getString("village");
						/* 7 */IMAGES[i][6] = json1.getString("latitude");
						/* 8 */IMAGES[i][7] = json1.getString("longitude");
						/* 9 */IMAGES[i][8] = json1.getString("unit_category");
						/* 10 */IMAGES[i][9] = json1.getString("cost");
						/* 11 */IMAGES[i][10] = json1.getString("last_name");
						/* 12 */IMAGES[i][11] = json1.getString("first_name");
						/* 13 */IMAGES[i][12] = json1.getString("phone");
					}

				} else {

					IMAGES = new String[1][1];
					IMAGES[0][0] = "No Results";
				}

				// if(success == 0){
				// IMAGES=new String[1][1];
				// IMAGES[0][0]="No Data";
				// }

			} catch (Exception e) {
				Log.e("FAILED TO PASS DATA", e.toString());
			}

			return null;
		}

		protected void onPostExecute(String file_url) {
			// dismiss the dialog after getting all products
			pDialog.dismiss();
			// updating UI from Background Thread
			runOnUiThread(new Runnable() {
				public void run() {
					/**
					 * Updating parsed JSON data into ListView
					 * */
					Log.d("DATA TRIAL", String.valueOf(IMAGES.length));
					if (IMAGES[0][0] != "No Results") {
						messageSearch = (TextView) findViewById(R.id.search_result_message);
						messageSearch.setText(IMAGES.length
								+ " Matching Results");
						list = (ListView) findViewById(R.id.listViewAllunits_search);
						adapter = new LazyAdapter(Search.this, IMAGES,
								ipOrDomain);
						list.setAdapter(adapter);
						list.setItemsCanFocus(true);
						list.setOnItemClickListener(new OnItemClickListener() {

							@Override
							public void onItemClick(AdapterView<?> parent,
									View view, int position, long id) {
								startingSingleUnit(position);
							}
						});
					} else {
						editor = (EditText) findViewById(R.id.searchform);
						messageSearch = (TextView) findViewById(R.id.search_result_message);
						messageSearch
								.setText("No Results For your search clue "
										+ editor.getText().toString()
										+ " Was found");
						Intent intent = new Intent(Search.this, Search.class);
						intent.putExtra(
								"MESSAGE",
								"No Results For your search clue "
										+ editor.getText().toString()
										+ " Was found. Below are Results from previous Search");
						list = (ListView) findViewById(R.id.listViewAllunits_search);
						list.setAdapter(null);
					}
				}
			});
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.search, menu);
		return true;
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.search__location:
			startlocationActivity();
			return true;
		case R.id.search_advanced:
			return true;
		case R.id.search_price:
			startPriceActivity();
			return true;
		case R.id.search_composition:
			return true;
		default:
			return false;
		}
	}

	private void startPriceActivity() {
		Bundle bundle = getIntent().getExtras();
		Intent intent = new Intent(this, SearchByPrice.class);
		intent.putExtra("CATEGORY_ID", bundle.getString("CATEGORY_ID"));
		intent.putExtra("CATEGORY_NANE", bundle.getString("CATEGORY_NAME"));
		startActivity(intent);
		finish();
	}

	private void startlocationActivity() {
		Bundle bundle = getIntent().getExtras();
		Intent intent = new Intent(this, SearchByLocation.class);
		intent.putExtra("CATEGORY_ID", bundle.getString("CATEGORY_ID"));
		intent.putExtra("CATEGORY_NANE", bundle.getString("CATEGORY_NAME"));
		startActivity(intent);
		finish();
	}

	// private void startCompositionActivity() {
	// Bundle bundle=getIntent().getExtras();
	// Intent intent = new Intent(this, SearchByLocation.class);
	// intent.putExtra("CATEGORY_ID", bundle.getString("CATEGORY_ID"));
	// intent.putExtra("CATEGORY_NANE", bundle.getString("CATEGORY_NAME"));
	// startActivity(intent);
	// finish();
	// }
	//
	// private void startAdvancedSearchActivity() {
	// Bundle bundle=getIntent().getExtras();
	// Intent intent = new Intent(this, SearchByLocation.class);
	// intent.putExtra("CATEGORY_ID", bundle.getString("CATEGORY_ID"));
	// intent.putExtra("CATEGORY_NANE", bundle.getString("CATEGORY_NAME"));
	// startActivity(intent);
	// finish();
	// }
}